package estore.service;

import estore.model.Product;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ProductService {
    private final Map<String, Product> productData = new HashMap<>();
    private String dataFilePath = "products.dat"; // 默认路径，避免配置文件缺失报错

    public ProductService() {
        try {
            loadConfig(); // 尝试加载配置
        } catch (Exception e) {
            System.out.println("配置文件加载失败，使用默认数据文件路径：" + dataFilePath);
        }
        try {
            loadData(); // 加载持久化数据
            if (productData.isEmpty()) {
                initDefaultProducts();
            }
        } catch (Exception e) {
            System.out.println("数据加载失败，初始化默认商品：" + e.getMessage());
            initDefaultProducts();
        }
    }

    public void addProduct(Product product) {
        if (product != null && !productData.containsKey(product.getId())) {
            productData.put(product.getId(), product);
        }
    }

    private void initDefaultProducts() {
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product("p003", "Python程序设计", 45.0, 200));
        productData.put("p004", new Product("p004", "Linux操作系统", 88.0, 0));
    }

    private void loadConfig() throws IOException {
        Properties properties = new Properties();
        File configFile = new File("config.properties");
        if (configFile.exists()) {
            try (InputStreamReader isr = new InputStreamReader(new FileInputStream(configFile), "UTF-8")) {
                properties.load(isr);
                dataFilePath = properties.getProperty("data.file.path", "products.dat");
            }
        } else {
            System.out.println("配置文件config.properties不存在，使用默认路径");
        }
    }

    public void saveData() throws IOException {
        File dataFile = new File(dataFilePath);
        boolean isAppend = dataFile.exists();
        try (FileOutputStream fos = new FileOutputStream(dataFile, isAppend);
             BufferedOutputStream bos = new BufferedOutputStream(fos);
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            if (isAppend) {
                bos.write("\n\n".getBytes());
                bos.flush();
            }
            oos.writeObject(productData);
            System.out.println(isAppend ? "数据追加成功" : "数据保存成功");
        }
    }

    @SuppressWarnings("unchecked")
    private void loadData() throws IOException, ClassNotFoundException {
        File dataFile = new File(dataFilePath);
        if (!dataFile.exists()) return;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFile))) {
            Map<String, Product> loadedData = (Map<String, Product>) ois.readObject();
            productData.clear();
            productData.putAll(loadedData);
            System.out.println("加载" + productData.size() + "个商品");
        }
    }

    public String getDataFilePath() {
        return dataFilePath;
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public Product findProductById(String id) {
        return productData.get(id);
    }

    public void updateStock(String productId, int newStock) {
        Product product = findProductById(productId);
        if (product != null) {
            product.setStock(newStock);
        }
    }
}